<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商店id" prop="storeId">
        <el-select v-model="queryParams.storeId" placeholder="请选择商店id" clearable>
          <el-option
            v-for="dict in dict.type.choose_store"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="宠物物种" prop="petSpecies">
        <el-input
          v-model="queryParams.petSpecies"
          placeholder="请输入宠物物种"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="宠物品种" prop="petBreed">
        <el-input
          v-model="queryParams.petBreed"
          placeholder="请输入宠物品种"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="宠物出售状态" prop="petStatus">
        <el-select v-model="queryParams.petStatus" placeholder="请选择宠物出售状态" clearable>
          <el-option
            v-for="dict in dict.type.pet_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['pets:pets:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['pets:pets:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['pets:pets:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['pets:pets:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="petsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="宠物id" align="center" prop="petId" />
      <el-table-column label="商店id" align="center" prop="storeId">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.choose_store" :value="scope.row.storeId"/>
        </template>
      </el-table-column>
      <el-table-column label="宠物名字" align="center" prop="petName" />
      <el-table-column label="宠物年龄" align="center" prop="petAge" />
      <el-table-column label="宠物性别" align="center" prop="petGender" />
      <el-table-column label="宠物物种" align="center" prop="petSpecies" />
      <el-table-column label="宠物品种" align="center" prop="petBreed" />
      <el-table-column label="宠物logo图" align="center" prop="petLogo" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.petLogo" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="宠物描述" align="center" prop="petDescription" />
      <el-table-column label="宠物价格" align="center" prop="petPrice" />
      <el-table-column label="宠物出售状态" align="center" prop="petStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pet_status" :value="scope.row.petStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['pets:pets:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['pets:pets:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleVideoPreview(scope.row)"
            v-hasPermi="['pets:pets:preview']"
          >视频预览</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改宠物对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商店id" prop="storeId">
          <el-select v-model="form.storeId" placeholder="请选择商店id">
            <el-option
              v-for="dict in dict.type.choose_store"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="宠物名字" prop="petName">
          <el-input v-model="form.petName" placeholder="请输入宠物名字" />
        </el-form-item>
        <el-form-item label="宠物年龄" prop="petAge">
          <el-input v-model="form.petAge" placeholder="请输入宠物年龄" />
        </el-form-item>
        <el-form-item label="宠物性别" prop="petGender">
          <el-input v-model="form.petGender" placeholder="请输入宠物性别" />
        </el-form-item>
        <el-form-item label="宠物物种" prop="petSpecies">
          <el-input v-model="form.petSpecies" placeholder="请输入宠物物种" />
        </el-form-item>
        <el-form-item label="宠物品种" prop="petBreed">
          <el-input v-model="form.petBreed" placeholder="请输入宠物品种" />
        </el-form-item>
        <el-form-item label="宠物logo图" prop="petLogo">
          <image-upload v-model="form.petLogo"/>
        </el-form-item>
        <el-form-item label="宠物描述" prop="petDescription">
          <el-input v-model="form.petDescription" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="视频标题" prop="videoTitle">
          <el-input v-model="form.videoTitle" placeholder="请输入视频标题" />
        </el-form-item>
        <el-form-item label="视频链接" prop="videoUrl">
          <el-upload :auto-upload="true" class="avatar-uploader el-upload--text" :headers="videoUpload.headers" :action="videoUpload.url" :show-file-list="false"
                     accept=".mp4"  :on-success="handleVideoSuccess"  :before-upload="beforeUploadVideo" :on-progress="uploadVideoProcess">
            <!--视频区域，:src里面存放视频上传成功后的存储地址-->
            <video width="250" v-if="this.showVideoPath !=='' && !videoFlag" :src="videoUpload.url2 + this.showVideoPath" class="avatar video-avatar" controls="controls" style="width:300px">
              您的浏览器不支持视频播放
            </video>
            <!-- 变量showVideoPath如果不存在，就不显示，存在就显示视频 -->
            <i v-else-if="this.showVideoPath ==='' && !videoFlag" class="el-icon-plus avatar-uploader-icon">
            </i>
            <!--上传进度条区域-->
            <el-progress :stroke-width="10" class="progressType" v-if="videoFlag === true"
                         type="circle" :percentage="videoUploadPercent" style="margin-top:30px;">
            </el-progress>
            <!--此为视频点击上传按钮 isShowUploadVideo代表按钮显示与否-->
            <el-button class="video-btn" slot="trigger" size="small" v-if="isShowUploadVideo" type="primary">点击上传视频</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item  style="position: relative ;">
          <el-input type="hidden" v-model="form.videoUrl" readonly class="noAlert" placeholder="" />
        </el-form-item>
        <el-form-item label="宠物价格" prop="petPrice">
          <el-input v-model="form.petPrice" placeholder="请输入宠物价格" />
        </el-form-item>
        <el-form-item label="宠物出售状态" prop="petStatus">
          <el-select v-model="form.petStatus" placeholder="请选择宠物出售状态">
            <el-option
              v-for="dict in dict.type.pet_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 使用<el-dialog>组件创建视频预览对话框 -->
    <el-dialog :visible.sync="videoVisible" :before-close="handleClose" title="视频预览" :align="'center'">
      <video width="500" controls>
        <source :src="videoUrl" type="video/mp4">
        您的浏览器不支持视频播放
      </video>
      <span slot="footer" class="dialog-footer">
        <el-button @click="videoVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listPets, getPets, delPets, addPets, updatePets } from "@/api/pets/pets";
import { getToken } from "@/utils/auth";
export default {
  name: "Pets",
  dicts: ['pet_status', 'choose_store'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 宠物表格数据
      petsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        storeId: null,
        petSpecies: null,
        petBreed: null,
        petStatus: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        storeId: [
          { required: true, message: "商店id不能为空", trigger: "change" }
        ],
        petName: [
          { required: true, message: "宠物名字不能为空", trigger: "blur" }
        ],
        petAge: [
          { required: true, message: "宠物年龄不能为空", trigger: "blur" }
        ],
        petGender: [
          { required: true, message: "宠物性别不能为空", trigger: "blur" }
        ],
        petSpecies: [
          { required: true, message: "宠物物种不能为空", trigger: "blur" }
        ],
        petBreed: [
          { required: true, message: "宠物品种不能为空", trigger: "blur" }
        ],
        videoTitle: [
          { required: true, message: "视频标题不能为空", trigger: "blur" }
        ],
        videoUrl: [
          { required: true, message: "视频链接不能为空", trigger: "blur" }
        ],
        petPrice: [
          { required: true, message: "宠物价格不能为空", trigger: "blur" }
        ],
        petStatus: [
          { required: true, message: "宠物出售状态不能为空", trigger: "change" }
        ]
      },
      //拿到当前环境的请求前缀
      videoUpload:{
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/uploadVideo",
        url2: process.env.VUE_APP_BASE_API,
      },
      showVideoPath: "",
      uploadUrl:"",//你要上传视频到你后台的地址
      videoFlag:false , //是否显示进度条
      videoUploadPercent:"", //进度条的进度，
      isShowUploadVideo:false, //显示上传按钮
      videoVisible: false,
      videoUrl: null // 视频URL将动态设置
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询宠物列表 */
    getList() {
      this.loading = true;
      listPets(this.queryParams).then(response => {
        this.petsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        petId: null,
        storeId: null,
        petName: null,
        petAge: null,
        petGender: null,
        petSpecies: null,
        petBreed: null,
        petLogo: null,
        petDescription: null,
        videoTitle: null,
        videoUrl: null,
        petPrice: null,
        petStatus: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.petId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加宠物";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const petId = row.petId || this.ids
      getPets(petId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改宠物";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.petId != null) {
            updatePets(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPets(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const petIds = row.petId || this.ids;
      this.$modal.confirm('是否确认删除宠物编号为"' + petIds + '"的数据项？').then(function() {
        return delPets(petIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('pets/pets/export', {
        ...this.queryParams
      }, `pets_${new Date().getTime()}.xlsx`)
    },
    //上传前回调
    beforeUploadVideo (file) {
      const isLt1024M = (file.size / 1024 / 1024) < 1024;
      this.form.videoSize = file.size / 1024 / 1024;
      //判断是不是MP4格式视频
      if (['video/mp4'].indexOf(file.type) !== 0) {
        this.$message.error('请上传正确的视频格式');
        return false;
      }
      //单个视频大小限制在1024M以内
      if (!isLt1024M ) {
        this.$message.error('上传视频大小不能超过1024MB哦!');
        return false;
      }
      this.isShowUploadVideo = false;
    },

    //进度条
    uploadVideoProcess (event, file, fileList) {
      this.videoFlag = true;
      this.videoUploadPercent = file.percentage.toFixed(0) * 1;
    },

    //上传成功回调
    handleVideoSuccess (res, file) {
      this.isShowUploadVideo = true;
      this.videoFlag = false;
      this.videoUploadPercent = 0;
      if(res !==""){
        this.showVideoPath = res;
        this.form.videoUrl = res;
      } else {
        this.$message.error('视频上传失败，请重新上传！');
      }
    },
    handleVideoPreview(row) {
      // 获取视频链接
      const videoUrl = process.env.VUE_APP_BASE_API + row.videoUrl;
      console.log(videoUrl);
      // 设置视频URL
      this.videoUrl = videoUrl;
      // 显示视频预览对话框
      this.videoVisible = true;
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {});
    }
  }
};
</script>
